<template>
  <view class="goods" style="overflow: hidden; height: 100vh">
    <!-- 搜索 -->
    <view class="search">
      <span class="headerText">{{
        headerText == '' ? '搜索' : headerText
      }}</span>
      <u-search
        bg-color="#fff"
        :show-action="false"
        placeholder="搜索商品"
        v-model="form.keywords"
        @change="onSearch"
        :border-color="search ? '#ff6c18' : ''"
        :focus="search ? true : false"
      ></u-search>
    </view>
    <!-- 工具 -->
    <view class="tools">
      <view @click="handleAll" :class="{ active_title: active === 0 }"
        >全部</view
      >
      <view @click="handleSales" :class="{ active_title: active === 1 }"
        >销量</view
      >
      <view class="sort-item" @click="handleSort('price')">
        <text :class="{ active_title: active === 2 }">价格</text>
        <view class="sort-icons">
          <u-icon
            name="arrow-up-fill"
            size="12"
            :color="
              sortType === 'price' && sortDirection === 'asc' && active === 2
                ? '#ff6c18'
                : '#999'
            "
          ></u-icon>
          <u-icon
            name="arrow-down-fill"
            size="12"
            :color="
              sortType === 'price' && sortDirection === 'desc' && active === 2
                ? '#ff6c18'
                : '#999'
            "
          ></u-icon>
        </view>
      </view>
      <view class="screen">
        <van-dropdown-menu
          :class="{ active_filter: active === 3 }"
          active-color="#ff6c18"
        >
          <van-dropdown-item title="筛选" ref="item">
            <view class="dropdown">
              <view class="dropdownTitle">全部分类</view>
              <view class="dropdownContent">
                <view
                  class="categoryItem" :class="{ active_title: activeCategory === item.name }"
                   @click="handleCategory(item,item.id,0)"
                  v-for="(item) in categoryList"
                  :key="item.id"
                >
                  {{ item.name }}
                </view>
              </view>
              <view class="dropdownTitle">价格区间</view>
              <view class="priceBox">
                <view
                  @click="handlePrice(value, index)"
                  class="priceItem"
                  :class="{ active_title: activePrice === index }"
                  v-for="(value, index) in priceList"
                  :key="index"
                >
                  {{ value }}
                </view>
              </view>

              <view class="priceBox center">
                <van-field
                  v-model="form.minMoneyQuery"
                  style="width: 200rpx; height: 70rpx"
                  :border="true"
                  type="digit"
                  placeholder="最低价"
                />
                <van-icon name="minus" />
                <van-field
                  v-model="form.maxMoneyQuery"
                  style="width: 200rpx; height: 70rpx; text-align: center"
                  :border="true"
                  type="digit"
                  placeholder="最高价"
                />
              </view>
              <view class="btnBox">
                <u-button
                  plain
                  type="primary"
                  class="btn  "
                  @click="clearnDropdown"

                  >重置</u-button
                >
                <u-button type="primary" class="btn" @click="closeDropdown"
                  >确定</u-button
                >
              </view>
            </view>
          </van-dropdown-item>
        </van-dropdown-menu>
      </view>
    </view>
    <!-- 分类 -->
    <view class="categoryBox">
      <view class="categorys">
        <view @click="handleCategory(item,item.id,1)" class="categoryItem" :class="{ active_title: activeCategory === item.name }" v-for="item in categoryList" :key="item.id">
          {{ item.name }}
        </view>
      </view>
 
    </view>
    <!-- 商品列表 -->
    <view class="goodsListBox" style="flex: 1">
      <scroll-view
        class="goods-scroll"
        scroll-y="true"
        @scroll="onScroll"
        :scroll-top="scrollViewTop"
        @scrolltolower="onScrollToLower"
        style="height: 100%"
      >
        <view class="scrollBox">
          <!-- 加载中 -->
          <u-loadmore
            v-if="pagination.loading"
            status="loading"
            icon-type="flower"
          />
          <view class="goodsList">
            <view
              class="goodsItem"
              @click="gotoGoodsDetail(item)"
              v-for="(item, index) in goodsList"
              :key="item.id || index"
            >
              <view class="goodsImg">
                <image
                  style="
                    width: 100%;
                    height: 100%;
                    border-top-left-radius: 10rpx;
                    border-top-right-radius: 10rpx;
                  "
                  :src="item.image"
                  mode=""
                ></image>
              </view>
              <view class="goodsBottom">
                <view class="goodsName">{{ item.name }}</view>
                <view class="goodsTitle">
                  <view class="title"
                    ><u-tag size="mini" text="厂商特卖" type="warning "
                  /></view>
                  <view class="subTitle">
                    全店已售<text>{{ item.saleCount }}</text
                    >件
                  </view>
                </view>
                <view>
                  <span class="goodsPrice">￥{{ item.currentUserMoney }}</span>
                  <span
                    class="original"
                    v-if="item.currentUserMoney != item.money"
                    >￥{{ item.money }}</span
                  >
                </view>
              </view>
            </view>
            <u-empty
              style="margin: auto; margin-top: 300rpx"
              v-if="goodsList.length === 0 && !pagination.loading"
              text="暂无商品~"
              mode="list"
            ></u-empty>
          </view>
          <view class="noMore" v-if="goodsList.length > 0">没有更多了~</view>
        </view>
      </scroll-view>
      <u-back-top @click="backTop" :scroll-top="scrollTopBack"></u-back-top>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
// api
import { productApi, baseApi } from '@/api'
// store
import { userGylCarStore, useUserStore } from '@/store'
import { sign } from 'crypto'
import { log } from 'console'
// 初始化数据
const isApp = ref()
const shopMode = ref()
const gylStore = userGylCarStore()
const shopId = ref(uni.getStorageSync('gylShopId'))
const headerText = ref('')
const search = ref(false)
const active = ref(0)
const goodsList = ref<any>([])
const form = ref({
  minMoneyQuery: '',
  maxMoneyQuery: '',
  sortJson: '',
  keywords: ''
})
const pagination = reactive({
  pageIndex: 1,
  pageSize: 8,
  total: 0,
  loading: false,
  noMoreData: false
})
const sortType = ref('')
const sortDirection = ref<'asc' | 'desc'>('asc')
const scrollViewTop = ref(0)
const scrollTopBack = ref(0)
const categoryId = ref(null)
const item = ref<any>(null)
const categoryList = ref<any>([])
const activeCategory = ref('')
const priceList = ref(['0-100', '100-500', '500-1000'])
const activePrice = ref(null)
// 初始化table
const initPagination = () => {
  pagination.pageIndex = 1
  pagination.total = 0
  pagination.noMoreData = false
  goodsList.value = [] // 旧数据清空
}

// 去空格
const trimKeywords = (keywords: string) => {
  return keywords.replace(/\s+/g, '')
}

// 获取商品列表
const getGoodsList = async (isLoadMore = false) => {
  if (pagination.loading) return // 真正在加载中才拦截
  if (!isLoadMore) initPagination() // 非“上拉加载”场景→重置分页

  pagination.loading = true
  try {
    const { data, code } = await productApi.getShopProductList({
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      categoryId: categoryId.value,
      shopId: shopId.value,
      ...form.value
    })
    if (code === 200) {
      pagination.total = data.total
      goodsList.value = isLoadMore
        ? [...goodsList.value, ...data.records]
        : data.records

      pagination.noMoreData =
        goodsList.value.length >= pagination.total ||
        data.records.length < pagination.pageSize
    }
  } catch (e: any) {
    console.error('获取商品列表失败:', e.msg)
  } finally {
    pagination.loading = false
  }
}
// 点击取商品详情
const gotoGoodsDetail = (item: any) => {
  if (shopMode.value && isApp.value) {
    uni.navigateTo({
      url: `/packageG/pages/goods/goodsDetail?id=${item.productId}&from=${isApp.value}&mode=${shopMode.value}`
    })
  } else {
    uni.navigateTo({
      url: `/packageG/pages/goods/goodsDetail?id=${item.productId}`
    })
  }
}

//搜索
const onSearch = () => {
  search.value = false
  form.value.keywords = trimKeywords(form.value.keywords)
  if (!form.value.keywords) {
    clearForm() // 清空所有筛选条件
  }
  getGoodsList()
}
// 清空form
const clearForm = () => {
  form.value = {
    maxMoneyQuery: '',
    minMoneyQuery: '',
    sortJson: '',
    keywords: ''
  }
}

const handleAll = () => {
  active.value = 0
  activeCategory.value = ''
  categoryId.value = null
  activePrice.value = null
  headerText.value = ''
  clearForm()
  getGoodsList()
}

const handleSales = () => {
  form.value.sortJson =
    '%5B{"column":"saleCount","direction":"DESC"},{"column":"id","direction":"DESC"}%5D'
  active.value = 1
  getGoodsList()
}

const handleSort = (type: string) => {
  active.value = 2
  if (sortType.value === type) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortType.value = type
    sortDirection.value = 'asc'
  }
  form.value.sortJson = `%5B{"column":"money","direction":"${sortDirection.value.toUpperCase()}"}%5D`
  getGoodsList()
}

// #region ************ 筛选内容 ********************** */

// 点击了分类  1：是首页单独点击分类，0是筛选里面带年纪
const handleCategory = (item: any,id: any,sign:any) => {
  activeCategory.value =  item.name
  categoryId.value = id
  if(sign == 1) {
    headerText.value = item.name
    active.value = 3
    getGoodsList()
  }
}
//清空
const clearnDropdown = () => {
  form.value.maxMoneyQuery = ''
  form.value.minMoneyQuery =  ''
  activeCategory.value = ''
  active.value = 0
  categoryId.value = null
  activePrice.value = null
  headerText.value = ''

  getGoodsList()
  item.value.toggle()
}
// 将选中的分类移动到可视区域
const scrollToActiveByIndex = () => {
  // #ifdef H5
  if (!activeCategory.value || categoryList.value.length === 0) {
    console.log('没有活动分类或分类列表为空')
    return
  }
  
  // 找到活动分类在列表中的索引
  const activeIndex = categoryList.value.findIndex((item: any) => 
    item.name === activeCategory.value
  )
  
  
  if (activeIndex === -1) {
    return
  }
  
  // 获取顶部导航中对应索引的元素
  const categoryItems = document.querySelectorAll('.categoryBox .categoryItem')
  if (activeIndex >= categoryItems.length) {
    console.log('索引超出范围')
    return
  }
  
  const targetElement = categoryItems[activeIndex]
  if (!targetElement) {
    console.log('未找到目标元素')
    return
  }
  
  console.log('准备滚动到元素:', targetElement.textContent)
  
  // 滚动到该元素
  targetElement.scrollIntoView({
    behavior: 'smooth',
    block: 'nearest',
    inline: 'center'
  })
  // #endif
}
// 确定
const closeDropdown = () => {
  active.value = 3
headerText.value = activeCategory.value
  getGoodsList()
  item.value.toggle()
  setTimeout(() => {
    scrollToActiveByIndex()
  }, 100)
}

// 价格区间选项
const handlePrice = (value: any, index: any) => {
  console.log(value, '价格区间')
  const [min, max] = value.split('-')

  form.value.minMoneyQuery = min
  form.value.maxMoneyQuery = max

  activePrice.value = index
}

// #endregion

const onScroll = (e: any) => {
  scrollTopBack.value = e.detail.scrollTop
}

const onScrollToLower = () => {
  pagination.pageIndex++
  getGoodsList(true)
}

const backTop = () => {
  scrollViewTop.value = 1
  setTimeout(() => {
    scrollViewTop.value = 0
  }, 10)
}

// #region ************ 获取分类列表 ********************** */

const getCategoryList = async () => {
  const { data } = await baseApi.getCategoryList({
    detail: true,
    id: 9500024
  })

  // 使用转换函数
  categoryList.value = data.records[0].items.map((item: any) => ({
    name: item.name,
    id: item.id
  }))
}

//#endregion

onLoad((option) => {
  console.log('分类的option', option)

  if (option?.mode) {
    console.log(option?.mode)

    shopMode.value = option.mode
    shopId.value = gylStore.setGYL_SHOP_Id(option.mode)
    uni.setStorageSync('shopMode', option.mode)
  }
  if (option?.from) {
    isApp.value = option.from
    uni.setStorageSync('isApp', option?.from)
  }
  if (option?.categoryId) {
    categoryId.value = option.categoryId
  }
  if (option?.name) {
    headerText.value = option.name
  }
  if (option?.search) {
    search.value = option.search === '1'
  }
  getGoodsList()
  getCategoryList()
})
</script>

<style lang="scss" scoped>
.goods {
  padding: 20rpx;
  height: 100%;
  display: flex;
  flex-direction: column;

  .search {
    height: 66rpx;

    display: flex;
    align-items: center;
    .headerText {
      margin-right: 20rpx;
      padding: 10rpx;
      font-size: 28rpx;
      font-weight: 700;
      background-image: url(../../static/Fill.png);
      background-repeat: no-repeat;
      background-position: center bottom; /* 水平居中，垂直距离底部5px */
    }
  }

  .tools {
    margin-top: 20rpx;
    height: 50rpx;

    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #6c6c6c;
    flex-shrink: 0;

    .sort-item {
      display: flex;
      align-items: center;
      cursor: pointer;

      text {
        margin-right: 10rpx;
        font-size: 28rpx;
      }

      .sort-icons {
        display: flex;
        flex-direction: column;
        align-items: center;

        .u-icon {
          margin: 5rpx 0;
        }
      }
    }
    .screen {
      overflow-y: auto;
      .dropdown {
        padding: 20rpx;
        .dropdownTitle {
          padding: 20rpx 0;
          color: #393939;
          font-weight: 700;
        }
        .dropdownContent {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          .categoryItem {
            white-space: nowrap;
            padding: 10rpx;
            margin: 20rpx;
            background-color: #f4f8fb;
            color: #393939;
            border-radius: 12rpx;
          }
        }
        .priceBox {
          display: flex;
          align-items: center;
        }
        .center {
          width: 100%;
          margin: 20rpx 120rpx;
        }
        .priceItem {
          margin: 10rpx;
          padding: 20rpx;
          background-color: #f4f8fb;
          border-radius: 20rpx;
          margin-bottom: 40rpx;
        }
      }
    }
  }
  .categoryBox {
  .categorys {
    display: flex;
    align-items: center;
    overflow-x: auto;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
    
    // 确保有足够空间滚动
    padding: 10rpx 0;
    
    &::-webkit-scrollbar {
      display: none;
    }
  }
  
  .categoryItem {
    white-space: nowrap;
    padding: 10rpx;
    margin: 10rpx;
    background-color: #fff;
    color: #393939;
    border-radius: 12rpx;
    flex-shrink: 0;
  }
}
  .goodsListBox {
    height: calc(100vh - 170rpx);
    margin-bottom: 40rpx;
    .goods-scroll {
      flex: 1;
      margin-top: 20rpx;
      margin-bottom: 40rpx;
      .scrollBox {
        height: 100vh;
        margin-bottom: 40rpx;
        .noMore {
          margin: 20rpx;
          text-align: center;
        }
      }
    }
  }

  .goodsList {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
    .goodsItem {
      width: 340rpx;
      border-radius: 20rpx;
      background: #fff;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
      .goodsImg {
        height: 340rpx;
      }
      .goodsBottom {
        padding: 20rpx;
      }
      .goodsName {
        height: 30rpx;
        font-size: 26rpx;
        overflow: hidden;
      }
      .goodsTitle {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 10rpx 0;
        .subTitle {
          display: flex;
          align-items: center;
          font-size: 20rpx;
          color: #999999;
          image {
            width: 30rpx;
            height: 30rpx;
            vertical-align: middle;
            margin-right: 10rpx;
          }
        }
      }
      .goodsPrice {
        font-size: 30rpx;
        font-weight: 700;
        color: #ef615b;
      }
      .original {
        margin: 0 15rpx;
        font-size: 24rpx;
        color: #999999;
        text-decoration: line-through;
      }
    }
  }

  .loading-status {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx;
    color: #999;
  }
}

.active_title {
  color: #ff6c18 !important;
}
.btnBox {
  display: flex;
  .btn {
    width: 50%;
  }
 
}

:deep(.van-dropdown-menu__bar) {
  background: none;
  box-shadow: none;
}
:deep(.van-dropdown-menu__title) {
  color: #999999;
}

.active_filter {
  :deep(.van-dropdown-menu__title) {
    color: #ff6c18 !important;
  }
}
:deep(.van-cell) {
  background: #f4f8fb;
  border-radius: 20rpx;
}

// :deep(.van-dropdown-menu__title) {
//   color: #333;
// }
</style>
